let debounce=require("lodash").debounce;
import React  from 'react';
import PropTypes from 'proptypes';
import Draggable from 'react-draggable';
import TableCell from './query-result-table-cell.jsx';
import PreviewModal from './preview-modal.jsx';
import { valueToString } from '../utils/convert';
import EditModal from './EditModal';
import SaveIcon from '@mui/icons-material/Save'
import FileCopyIcon from '@mui/icons-material/FileCopy'
import GridOnIcon from '@mui/icons-material/GridOn'
import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import { DataGrid } from '@mui/x-data-grid';


export default function QueryResultTable(props){
    const [state,setState]=React.useState({
      columnWidths: {},
      autoColumnWidths: [],
      showPreview: false,
      showEdit: false,
      pos: null,
    });
  React.useEffect(()=>{
    setState((state)=>({...state, showCopied: true }));
    setTimeout(() => setState((state)=>({...state, showCopied: false })), 3000);
  },[props.copied])
  React.useEffect(()=>{
    setState((state)=>({...state, showSaved: true }));
    setTimeout(() =>{setState((state)=>({...state, showSaved: false }));}, 3000);
  },[props.saved])

  const onColumnResizeEndCallback=(newColumnWidth, columnKey)=> {
    setState(({ columnWidths }) => ({
      columnWidths: {
        ...columnWidths,
        [columnKey]: newColumnWidth,
      },
    }));
  }

  const onOpenPreviewClick = value => {
    setState({ showPreview: true, valuePreview: value });
  };
  const onEditClick = (row, col) => {
    console.log(row + ',' + col);
    console.log(this);

    setState({ showEdit: true, pos: { row: row, col: col } });
  };
  const onClosePreviewClick = () => {
    setState({ showPreview: false, valuePreview: null });
  };
  const onCloseEditClick = () => {
    setState({ showEdit: false, pos: null });
  };
  const onResize=()=> {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resize, 16);
  }

  const getTextWidth=(text, font) =>{
    // additional spacing
    const padding = 28;
    const element = document.createElement('canvas');
    const context = element.getContext('2d');
    context.font = font;
    return context.measureText(text).width + padding;
  }
  const renderNoRows=()=> {
    return (
      <div style={{ textAlign: 'center', fontSize: '16px' }}>
        No results found
      </div>
    );
  }

  const handleStop=(data, e, move)=> {
    const { columnWidths } = state;
    const originalWidth = getColumnWidth(data);

    // update dragged column width
    setState({
      columnWidths: {
        ...columnWidths,
        [data.name]: Math.max(originalWidth + move.x, 10),
      },
    });

    if (headerdiv) {
      headerdiv.measureAllCells();
      headerdiv.recomputedivSize();
      headerdiv.forceUpdate();
    }

    if (rowsdiv) {
      rowsdiv.measureAllCells();
      rowsdiv.recomputedivSize();
      rowsdiv.forceUpdate();
    }
  }

  const renderHeaderTopBar=()=> {
    const {
      rows,
      rowCount,
      onCopyToClipboardClick,
      onSaveToFileClick,
    } = props;

    let copyPanel = null;
    let savePanel = null;
    if (rowCount) {
      copyPanel = (
        <div
          className="ui small label"
          title="Copy as"
          style={{ float: 'right', margin: '3px' }}
        >
          <FileCopyIcon />
          <Button
            className="detail"
            onClick={() => onCopyToClipboardClick(rows, 'CSV')}
          >
            CSV
          </Button>
          <Button
            className="detail"
            onClick={() => onCopyToClipboardClick(rows, 'JSON')}
          >
            JSON
          </Button>
        </div>
      );

      savePanel = (
        <div
          className="ui small label"
          title="Save as"
          style={{ float: 'right', margin: '3px' }}
        >
          <SaveIcon />
          <Button
            className="detail"
            onClick={() => onSaveToFileClick(rows, 'CSV')}
          >
            CSV
          </Button>
          <Button
            className="detail"
            onClick={() => onSaveToFileClick(rows, 'JSON')}
          >
            JSON
          </Button>
        </div>
      );
    }

    return (
      <div style={{ background: 'rgba(0, 0, 0, 0.05)', overflow: 'hidden' }}>
        <div className="ui label" style={{ margin: '3px', float: 'left' }}>
          <GridOnIcon />
          Rows
          <div className="detail">{rowCount}</div>
        </div>
        {savePanel}
        {copyPanel}
      </div>
    );
  }
  const renderEditModal=()=> {
    if (!state.showEdit) {
      return null;
    }

    return (
      <EditModal
        modalOpen={state.showEdit}
        pos={state.pos}
        onCloseClick={onCloseEditClick}
      />
    );
  }
  const renderPreviewModal=()=> {
    if (!state.showPreview) {
      return null;
    }

    return (
      <PreviewModal
        modalOpen={state.showPreview}
        value={state.valuePreview}
        onCloseClick={onClosePreviewClick}
      />
    );
  }

  const renderTableBody=(onScroll)=> {
    const { rowCount, fields } = props;
    const { tableWidth, tableHeight } = state;

    const headerHeight = 62; // value of 2 headers together
    const scrollBarHeight = 15;
    const rowHeight = 28;
    const fixedHeightRows = (rowCount || 1) * rowHeight + scrollBarHeight;
    let view_rows=props.rows.map((item,idx)=>{
      let view_fields=fields.map((field,idx2)=>
        (
      <TableCell
        key={idx2}
        rowIndex={idx}
        data={props.rows}
        col={field.name}
        onOpenPreviewClick={onOpenPreviewClick}
        onDeleteClick={() => {
          console.log('delete');
          // console.log(props.rows[idx]);
          props.onDeleteClick(props.rows[idx])
        }}
        onEditClick={() => {
          console.log('edit');
        }}
      />
        ));
      return <tr key={idx}>{view_fields}</tr>  
    });
    return(view_rows)
    return (
      <div
        className="div-body"
        ref={ref => {
          rowsdiv = ref;
        }}
        cellRenderer={renderCell}
        width={tableWidth}
        height={Math.min(tableHeight - headerHeight, fixedHeightRows)}
        rowHeight={rowHeight}
        onScroll={onScroll}
        rowCount={rowCount}
        columnCount={fields.length}
        columnWidth={getColumnWidth}
        rowsCount={rowCount}
        noContentRenderer={renderNoRows}
      />
    );
  }

  const renderTableHeader=(scrollLeft) =>{
    const { fields } = props;
    const { tableWidth } = state;

    if (!fields.length) {
      return null;
    }
    let view_fields=fields.map((item,idx)=>(<td key={idx}>{item.name}</td>));
    return(<tr>{view_fields}</tr>)
    return (
      <div
        ref={ref => {
          headerdiv = ref;
        }}
        columnWidth={getColumnWidth}
        columnCount={fields.length}
        height={30}
        cellRenderer={renderHeaderCell}
        className={'Headerdiv'}
        rowHeight={30}
        rowCount={1}
        getScrollbarSize={() => {
          return 0;
        }}
        width={tableWidth - scrollbarSize()}
        scrollLeft={scrollLeft}
      />
    );
  }
  const { fields,rows } = props;
  const { tableWidth } = state;
  let columns=fields.map((item,index)=>{//name: 'A', key: 0
    // return {field:item.key,lastName:item.name,firstName:item.name,age:item.key}
    return({
      field: ""+item.name,
      headerName: item.name,
      description: 'This column has a value getter and is not sortable.',
      sortable: false,
      width: 160,
      // valueGetter: (value, row) => `${row.firstName || ''} ${row.lastName || ''}`,
    })
  })
  let rows2=rows.map((item,index)=>{//name: 'A', key: 0
    let one={
      id:index,
      ...item
    }
    console.log(one);
    return(one)
  })
    return (
      <div>
        {renderHeaderTopBar()}
        {renderPreviewModal()}
        {renderEditModal()}
        <div>
            <Box sx={{ height: 600, width: '100%' }}>
              <DataGrid
                rows={rows2}
                columns={columns}
                checkboxSelection
                disableRowSelectionOnClick
              />
            </Box>
        </div>
      </div>
    );
  }
// react-dom.development.js:67 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.